<template>
    <table>
        <tbody>
            <tr>
                <td>图书名称：</td>
                <td>
                    <input type="text" id="bookName" v-model="obj.bookName">
                </td>
            </tr>
            <tr>
                <td>作者：</td>
                <td>
                    <input type="text" id="author" v-model="obj.author">
                </td>
            </tr>
            <tr>
                <td><input type="button" value="保存" @click="btnSave"></td>
                <td><input type="button" value="取消" @click="btnCancel"></td>
            </tr>
        </tbody>
    </table>
</template>

<script setup>
import { addItem, editItem, getById } from '@/api/bookApi';
import { onMounted, reactive } from 'vue';
import { useRouter,useRoute } from 'vue-router';

let router = useRouter()
let route = useRoute()

// --- 响应式数据 开始 ---
let obj = reactive({
    bookName:'',
    author:''
})
// --- 响应式数据 结束 ---


// --- 动作逻辑 开始 ---
async function btnSave(){
    // console.log('保存');
    let id = route.params.id || 0
    let data
    if(id){
        data = await editItem(id,obj)
    }else{
        data = await addItem(obj)
    }

    if(data.code === 1000){
        router.push('/book')
    }else{
        console.log(data.msg);
    }
}

function btnCancel(){
    // console.log('取消');
    router.push('/book')
}
// --- 动作逻辑 结束 ---


// --- 生命周期函数 开始 ---
onMounted(async () => {
    let id = route.params.id || 0
    // 获取对应id的内容
    let data = await getById(id)
    // 将获取的数据 填入对应文本框
    Object.assign(obj,data.data)
})
// --- 生命周期函数 结束 ---
</script>